var url = "/openx/channel/channelRule/listChannelRule"; isInit = false;

//对应接口入参
var param = {};

var formId = 'ruleQueryForm';

var selfUpdate;

// (function () {

//     /**进行表格数据初始化*/
//     $.openx.initTable("table", url, param);
// })();

//初始化表格
(function () {
    $(".chosen-select-no-single").chosen({ disable_search_threshold: 10 });

    var data = $.openx.getJsonObj(formId);
    //取个随机数查询，使第一次查询为空
    data.channelCodes = 'fdsfasxxx56236589' + '-' + new Date().getTime();
    param.channelRuleParam = data;
    $.openx.initTable("table", url, param);
    $("#channelCodeImport").yfChannel({
        url: ecp_boss_server + '/openx/boss/channelService/listChannelTree',
        filter: 'root'
    });
    $("#channelCode").yfChannel({
        url: ecp_boss_server + '/openx/boss/channelService/listChannelTree',
        filter: 'leaves'
    });
    /**设置增删改查的工具条*/
    $.openx.setTableToolBar('partnerbar');

})();

function search() {
    if (!isInit) {
        isInit = true;

    }
    var channelList_data = $("#channelCode").yfChannel("getData");
    if (channelList_data.length == 0) {
        layer.msg("请选择渠道！");
        return;
    }
    refreshTable();
}

function refreshTable() {
    var channelCode = [];
    var channelList_data = $("#channelCode").yfChannel("getData");
    if (channelList_data.length > 0) {
        $.each(channelList_data, function (i, item) {
            channelCode.push(item.displayChannel);
        });
    }
    $("#channelCodes").val(channelCode.join(","));
    var data = $.openx.getJsonObj(formId);
    param.channelRuleParam = data;
    $.openx.tableRefresh(url, param, true);
}

function resetForm() {
    $('#ruleQueryForm')[0].reset();
    $("#channelCode").yfChannel("reset");
}

function dateFormat(value) {
    return !value ? "-" : new Date(value).format("yyyy-MM-dd hh:mm")
}


function statusFormat(v, row) {
    var id = row.id + new Date().getTime();
    var html = '<div class="switch">';
    html += '<div class="onoffswitch" style="width:100px;padding-left:30px">';
    if (row.status === 'ENABLE') {
        html += "<input type='checkbox'  checked class='onoffswitch-checkbox' onclick ='javascript:changeDeliveryStatus(" + JSON.stringify(row) + ")'  id='" + id + "'>";
    } else {
        html += "<input type='checkbox'  class='onoffswitch-checkbox' onclick ='javascript:changeDeliveryStatus(" + JSON.stringify(row) + ")'  id='" + id + "'>";
    }
    html += '<label class="onoffswitch-label" for="' + id + '">';
    html += '<span class="onoffswitch-inner"></span>';
    html += '<span class="onoffswitch-switch"></span>';
    html += '</label>';
    html += '</div>';
    html += '</div>';
    return html;
}

function changeDeliveryStatus(row) {
    $X("/channel/channelRule", "enableOrDisableStatus").callx({
        id: row.id,
        onResult: function (data) {
            if (data) {
                $.openx.tableRefresh(null, null, true);
                layer.closeAll();
                layer.msg("修改成功");
            }
        },
        onError: function (error) {
            var res = JSON.parse(error);
            layer.msg(res.message)
        }
    });
}

$.openx.insert = function () {
    //初始化数据
    $("#contain1>div:gt(0)").remove()
    setEmpty($("#divRow"))
    $('#ruleCode1').val('');
    $('#ruleName').val('');
    $('#ruleRemark').val('');
    $("#addUpdateTpl").modal("show");
    
}

$.openx.update = function () {

    $("#contain2>div:gt(0)").remove()
    setEmpty($("#divRow2"))
    $('#ruleCode2').val('');
    $('#ruleName2').val('');
    $('#ruleRemark2').val('');
    
    $.openx.onClickUpdate(function (row) {
        if(row.length ===1){
            $("#updateTpl").modal("show");
        }
        $('#ruleCode2').val(row[0].ruleCode);
        selfUpdate = row[0].ruleCode;
        $('#ruleName2').val(row[0].ruleName);
        $('#ruleRemark2').val(row[0].ruleRemark);
        $('#channelCodeImport2').val(row[0].channelCode);
        $('#ruleId').val(row[0].id);
        $X("/channel/channelRule", "listRuleDetail").callx({
            id: row[0].id,
            onResult: function (result) {
                if (result) {
                    for(var i=0;i<result.length;i++){
                        if(i == 0){
                            $("#divRow2").find("input[name='key']").val(result[i].key); 
                            $("#divRow2").find("input[name='value']").val(result[i].value); 
                        }else{
                            var html = $("#divRow2").clone();
                            setKeyValue(html,result[i]);
                            $(html).find("button[name='deleteRow']").attr('disabled',false);
                            $("#contain2").append(html);
                        }
                    }
                }
                
          },
          onError: function (error) {
            error = JSON.parse(error)
            layer.msg(error.message || "更新失败");
          }
        });
    });
    
}


$.openx.delete = function () {
    $.openx.onClickDelete(function (row) {
        if(row.length == 0){
            layer.msg("请选择需要删除的数据");
        }
        var ids = $.openx.getArrays('id',row);
        $X("/channel/channelRule", "deleteChannelRule").callx({
            ids: ids,
            onResult: function (result) {
                layer.msg("删除成功");
                refreshTable();
            },
            onError: function (error) {
                error = JSON.parse(error)
                layer.msg(error.message || "添加失败");
            }
        });
    });
}

function submitTo() {

     var formId = 'addRuleForm';
    var importChannelCodeList = [];
    var channelList_data = $("#channelCodeImport").yfChannel("getData");
    if (channelList_data.length > 0) {
        $.each(channelList_data, function (i, item) {
            importChannelCodeList.push(item.displayChannel);
        });
    };
    if (importChannelCodeList == '') {
        layer.tips("请选择渠道", "#channelCodeImport", {
            tips: [2, "#f40"]
        })
        return;
    } else {
        $("#channelCodesImport").val(importChannelCodeList.join(","));
    }
    


    var detailList = [];
    var checkKey = [];
    var errorCode ;
    $("#contain1>div").each(function(index,item){
        var key =  $(item).find("input[name='key']").val();
        if(checkKey.indexOf(key) == -1){
            checkKey.push(key);
        }else{
            $(item).find("input[name='key']").attr("id","key"+index);
            layer.tips("key值不能重复", "#key"+index, {
                tips: [2, "#f40"]
            })
            errorCode = true;
        }
        var value =  $(item).find("input[name='value']").val();
        if(key == ""){
            $(item).find("input[name='key']").attr("id","key"+index);
            layer.tips("key值不能为空", "#key"+index, {
                tips: [2, "#f40"]
            })
            errorCode = true;
        }
        if(value == ""){
            $(item).find("input[name='value']").attr("id","value"+index);
            layer.tips("value值不能为空", "#value"+index, {
                tips: [2, "#f40"]
            })
            errorCode = true;
        }
        if(value.length > 2000){
            $(item).find("input[name='value']").attr("id","value"+index);
            layer.tips("value值长度不能超过2000", "#value"+index, {
                tips: [2, "#f40"]
            })
            errorCode = true;
        }
        var object = new Object();
        object.key = key
        object.value=value
        detailList.push(object);
    })

    if(errorCode){
        return ;
    }

    console.log(detailList);
    if ($.openx.validation(formId)) {
         var channelRuleParam = new Object();
         channelRuleParam.channelCodes = $("#channelCodesImport").val();
         channelRuleParam.ruleCode = $("#ruleCode1").val();
         channelRuleParam.ruleName = $("#ruleName").val();
         channelRuleParam.ruleRemark = $('#ruleRemark').val();
         channelRuleParam.detailList = detailList;
         $X("/channel/channelRule", "addChannelRule").callx({
            channelRuleParam: channelRuleParam,
            onResult: function (data) {
                if (data) {
                    $.openx.tableRefresh(null, null, true);
                    $("#addUpdateTpl").modal("hide");
                    layer.msg("新增成功");
                }
          },
          onError: function (error) {
            error = JSON.parse(error)
            layer.msg(error.message || "添加失败");
          }
        });
    }
    
}

function addOther() {
    var html = $("#divRow").clone();
    setEmpty(html)
    $(html).find("button[name='deleteRow']").attr('disabled',false);
    $("#contain1").append(html)
}


function setEmpty(obj){
    $(obj).find("input[name='key']").val('');
    $(obj).find("input[name='value']").val('');
    
}

function setKeyValue(obj,result){
    $(obj).find("input[name='key']").val(result.key);
    $(obj).find("input[name='value']").val(result.value);
}


function submitUpdate() {
    
         var formId = 'updateRuleForm';
    
        var detailList = [];
        var checkKey = [];
        var errorCode ;
        $("#contain2>div").each(function(index,item){
            var key =  $(item).find("input[name='key']").val();
            if(checkKey.indexOf(key) == -1){
                checkKey.push(key);
            }else{
                $(item).find("input[name='key']").attr("id","key"+index);
                layer.tips("key值不能重复", "#key"+index, {
                    tips: [2, "#f40"]
                })
                errorCode = true;
            }
            var value =  $(item).find("input[name='value']").val();
            if(key == ""){
                $(item).find("input[name='key']").attr("id","key"+index);
                layer.tips("key值不能为空", "#key"+index, {
                    tips: [2, "#f40"]
                })
                errorCode = true;
            }
            if(value == ""){
                $(item).find("input[name='value']").attr("id","value"+index);
                layer.tips("value值不能为空", "#value"+index, {
                    tips: [2, "#f40"]
                })
                errorCode = true;
            }

            var object = new Object();
            object.key = key
            object.value=value
            detailList.push(object);
        })
    
        if(errorCode){
            return ;
        }
    
        console.log(detailList);
        if ($.openx.validation(formId)) {
             var channelRuleParam = new Object();
             channelRuleParam.channelCodes = $("#channelCodeImport2").val();
             channelRuleParam.ruleCode = $("#ruleCode2").val();
             if(selfUpdate === channelRuleParam.ruleCode){
                channelRuleParam.selfUpdate = 'Y';
             }else{
                channelRuleParam.selfUpdate = 'N';
             }
             channelRuleParam.ruleName = $("#ruleName2").val();
             channelRuleParam.ruleRemark = $('#ruleRemark2').val();
             channelRuleParam.ruleId = $('#ruleId').val();
             channelRuleParam.detailList = detailList;
             $X("/channel/channelRule", "updateChannelRule").callx({
                channelRuleParam: channelRuleParam,
                onResult: function (result) {
                    if (result) {
                        $.openx.tableRefresh(null, null, true);
                        $("#updateTpl").modal("hide");
                        layer.msg("更新成功");
                    }
              },
              onError: function (error) {
                error = JSON.parse(error)
                layer.msg(error.message || "添加失败");
              }
            });
        }
        
    }

    function addOther2() {
        var html = $("#divRow2").clone();
        setEmpty(html)
        $(html).find("button[name='deleteRow']").attr('disabled',false);
        $("#contain2").append(html)
    }

    /**删除*/
function deleteRowsData(tr) {
    $(tr).remove();
}